﻿using Abp.Application.Services;
using Abp.Runtime.Caching;
using Abp.Web.Models;
using Batman.Open.Accounts.Models;
using Batman.Open.Accounts.Readers;
using Newtonsoft.Json;
using System.Net;

namespace Batman.Open.Accounts.Handles
{
    public class WeixinHandler : ApplicationService
    {
        private const string cache_name = "WeixinHandler";

        public ICacheManager cacheManager { get; set; }

        public WeixinMiniProgramAccountReader weixinMiniProgramAccountReader { get; set; }

        /// <summary>
        /// 微信小程序 用code换取用户身份信息
        /// </summary>
        /// <returns></returns>
        public AjaxResponse<Code2SessionResponse> Code2Seesion(string appId, string code)
        {
            var result = cacheManager.GetCache(cache_name).GetOrDefault(code) as Code2SessionResponse;

            if (result == null)
            {
                var account = weixinMiniProgramAccountReader.GetAccount(appId);

                // todo: 处理下account空的判断
                var weixinMiniCode2SessionUrl = $"https://api.weixin.qq.com/sns/jscode2session?appid={ account.AppId }&secret={ account.Secret }&js_code={ code }&grant_type=authorization_code";

                using (var client = new WebClient())
                {
                    var responseString = client.DownloadString(weixinMiniCode2SessionUrl);

                    result = JsonConvert.DeserializeObject<Code2SessionResponse>(responseString);

                    // 只有请求成功才能写入缓存
                    if (result.errcode == Code2SessionError.请求成功)
                    {
                        cacheManager.GetCache(cache_name).Set(code, result);
                    }
                }
            }

            if (result.errcode == Code2SessionError.请求成功)
            {
                return new AjaxResponse<Code2SessionResponse>(true) { Result = result };
            }

            return new AjaxResponse<Code2SessionResponse>(false) { Error = new ErrorInfo(result.errMsg) };
        }
    }
}
